package com.sudichina.sudichina.choosecity;


import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.help.Inputtips;
import com.amap.api.services.help.InputtipsQuery;
import com.amap.api.services.help.Tip;
import com.sudichina.sudichina.MyApp;
import com.sudichina.sudichina.R;
import com.sudichina.sudichina.bean.City;
import com.sudichina.sudichina.choosecity.adapter.CityListAdapter;
import com.sudichina.sudichina.choosecity.adapter.ResultListAdapter;
import com.sudichina.sudichina.choosecity.db.DBManager;
import com.sudichina.sudichina.choosecity.model.LocateState;
import com.sudichina.sudichina.choosecity.utils.StringUtils;
import com.sudichina.sudichina.choosecity.view.SideLetterBar;
import com.sudichina.sudichina.entity.ReleaseRoute;
import com.sudichina.sudichina.utils.SpUtils;
import com.sudichina.sudichina.utils.Toastutils;
import com.sudichina.sudichina.view.activity.SelectCalendarActivity;
import com.sudichina.sudichina.view.activity.main.BaseActivity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * author zaaach on 2016/1/26.
 */
public class CityPickerActivity extends BaseActivity implements View.OnClickListener {
    public static final int REQUEST_CODE_PICK_CITY = 2333;
    public static final String KEY_PICKED_CITY = "picked_city";
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_right)
    TextView tvRight;
    @BindView(R.id.tv_city_name)
    TextView privateTvCityName;

    @BindView(R.id.ll_city)
    LinearLayout privateLlCity;
    @BindView(R.id.et_search)
    EditText privateEtSearch;
    @BindView(R.id.iv_search_clear)
    ImageView privateIvSearchClear;
    @BindView(R.id.listview_all_city)
    ListView privateListviewAllCity;
    @BindView(R.id.tv_letter_overlay)
    TextView privateTvLetterOverlay;
    @BindView(R.id.side_letter_bar)
    SideLetterBar privateSideLetterBar;
    @BindView(R.id.listview_search_result)
    ListView privateListviewSearchResult;
    @BindView(R.id.empty_view)
    LinearLayout privateEmptyView;
    @BindView(R.id.et_search_city)
    EditText privateEtSearchCity;
    @BindView(R.id.ll_scity)
    LinearLayout privateLlScity;
    @BindView(R.id.inputlist)
    ListView minputlist;

    private ListView mListView;
    private ListView mResultListView;
    private SideLetterBar mLetterBar;

    private ImageView clearBtn;

    private ViewGroup emptyView;

    private CityListAdapter mCityAdapter;
    private ResultListAdapter mResultAdapter;
    private List<City> mAllCities;
    private DBManager dbManager;

    private AMapLocationClient mLocationClient;

    private List<HashMap<String, String>> listString;
    private ReleaseRoute releaseRoute;

    private int TAG;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_city_list);
        ButterKnife.bind(this);
        final Intent intent = getIntent();

        releaseRoute = (ReleaseRoute) intent.getSerializableExtra("releaseRoute");
        System.out.println(releaseRoute.getFromAddress() + releaseRoute.getFromZoneCode());

        if (releaseRoute.getFromAddress() == null || releaseRoute.getFromZoneCode() == null) {
//选择出发地址
            TAG = 0;
            tvTitle.setText("选择出发城市");
        } else {
            //选择到达地
            TAG = 1;
            tvTitle.setText("选择到达城市");
        }


        privateLlCity.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //隐藏自己 打开输入框
                privateLlCity.setVisibility(View.GONE);
                privateLlScity.setVisibility(View.VISIBLE);
                if (minputlist.getVisibility() == View.VISIBLE) {
                    minputlist.setVisibility(View.GONE);
                }

            }
        });

        privateEtSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                privateLlCity.setVisibility(View.VISIBLE);
                privateLlScity.setVisibility(View.GONE);

            }
        });
        privateEtSearchCity.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                privateEtSearchCity.setFocusable(true);


            }
        });

        initData();
        initView();
        initLocation();

        privateEtSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (minputlist.getVisibility() == View.GONE) {
                    minputlist.setVisibility(View.VISIBLE);
                }
                /**输入后**/
                String key = s.toString().trim();
                String city = privateTvCityName.getText().toString().trim();
                InputtipsQuery inputquery = new InputtipsQuery(key, city);
                inputquery.setCityLimit(true);
                Inputtips inputTips = new Inputtips(CityPickerActivity.this, inputquery);

                inputTips.setInputtipsListener(new Inputtips.InputtipsListener() {
                    @Override
                    public void onGetInputtips(final List<Tip> tipList, int rCode) {
                        if (rCode == AMapException.CODE_AMAP_SUCCESS) {
                            listString = new ArrayList<HashMap<String, String>>();
                            for (int i = 0; i < tipList.size(); i++) {
                                HashMap<String, String> map = new HashMap<String, String>();
                                map.put("name", tipList.get(i).getName());
                                map.put("address", tipList.get(i).getDistrict());
                                listString.add(map);
                            }
                            SimpleAdapter aAdapter = new SimpleAdapter(getApplicationContext(), listString, R.layout.item_layout,
                                    new String[]{"name", "address"}, new int[]{R.id.poi_field_id, R.id.poi_value_id});

                            minputlist.setAdapter(aAdapter);
                            aAdapter.notifyDataSetChanged();

                        } else {
                            Toastutils.showToast("" + rCode);
                        }


                    }
                });
                inputTips.requestInputtipsAsyn();


            }

            @Override
            public void afterTextChanged(Editable s) {


            }

        });

        minputlist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
                final String address = listString.get(position).get("name");
                privateEtSearch.setText(address);
                listString = null;
                minputlist.setVisibility(View.GONE);
                com.sudichina.sudichina.querydatabase.DBManager dbManager = new com.sudichina.sudichina.querydatabase.DBManager(CityPickerActivity.this);

                String code = null;
                try {
                    code = dbManager.getCityFromCityName(privateTvCityName.getText().toString().trim()).getId();

                } catch (Exception e) {

                }
                if (TAG == 0) {

                    //现在是出发地的界面  接下来需要跳转的是目的地的界面
                    releaseRoute.setFromAddress(privateTvCityName.getText().toString().trim());
                    releaseRoute.setFromZoneCode(code);
                    Intent intent = new Intent(CityPickerActivity.this, CityPickerActivity.class);
                    intent.putExtra("releaseRoute", releaseRoute);

                    startActivity(intent);
                    finish();
                } else if (TAG == 1) {
                    //现在是目的地的界面 现在要跳转到时间选择的界面
//
                    releaseRoute.setToZoneCode(code);
//
                    SpUtils.putString(MyApp.getContext(), "releaseRouteToZoneAddress", MycityName + address);
                    SpUtils.putString(MyApp.getContext(), "releaseRouteToZoneAddress1", MycityName);

                    Intent intent = new Intent(CityPickerActivity.this, SelectCalendarActivity.class);


                    intent.putExtra("releaseRoute", releaseRoute);

                    startActivity(intent);
                    finish();
                }


            }
        });
    }

    private void initLocation() {
        mLocationClient = new AMapLocationClient(this);
        AMapLocationClientOption option = new AMapLocationClientOption();
        option.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        option.setOnceLocation(true);
        mLocationClient.setLocationOption(option);
        mLocationClient.setLocationListener(new AMapLocationListener() {
            @Override
            public void onLocationChanged(AMapLocation aMapLocation) {
                if (aMapLocation != null) {
                    if (aMapLocation.getErrorCode() == 0) {
                        String city = aMapLocation.getCity();
                        String district = aMapLocation.getDistrict();
                        Log.e("onLocationChanged", "city: " + city);
                        Log.e("onLocationChanged", "district: " + district);
                        String location = StringUtils.extractLocation(city, district);
                        mCityAdapter.updateLocateState(LocateState.SUCCESS, location);
                        MycityName = city;
                    } else {
                        //定位失败
                        mCityAdapter.updateLocateState(LocateState.FAILED, null);
                    }
                }
            }
        });
        mLocationClient.startLocation();
    }

    private String MycityName = null;

    private void initData() {
        dbManager = new DBManager(this);

        mAllCities = dbManager.getAllCities();
        mCityAdapter = new CityListAdapter(this, mAllCities);
        mCityAdapter.setOnCityClickListener(new CityListAdapter.OnCityClickListener() {
            @Override
            public void onCityClick(String name) {

                MycityName = name;
                //设置当前的城市
                privateTvCityName.setText(name);

                privateLlScity.setVisibility(View.GONE);
                privateLlCity.setVisibility(View.VISIBLE);

                privateEtSearch.setFocusable(true);
                privateEtSearch.requestFocus();
                privateEtSearch.requestFocusFromTouch();
// TODO: 2017/3/29 城市选择好了 显示搜索的列表
                if (minputlist.getVisibility() == View.GONE) {
                    minputlist.setVisibility(View.VISIBLE);
                }


                String city = privateTvCityName.getText().toString().trim();
                String key = city;
                InputtipsQuery inputquery = new InputtipsQuery(key, city);
                inputquery.setCityLimit(true);
                Inputtips inputTips = new Inputtips(CityPickerActivity.this, inputquery);

                inputTips.setInputtipsListener(new Inputtips.InputtipsListener() {
                    @Override
                    public void onGetInputtips(final List<Tip> tipList, int rCode) {
                        if (rCode == AMapException.CODE_AMAP_SUCCESS) {
                            listString = new ArrayList<HashMap<String, String>>();
                            for (int i = 0; i < tipList.size(); i++) {
                                HashMap<String, String> map = new HashMap<String, String>();
                                map.put("name", tipList.get(i).getName());
                                map.put("address", tipList.get(i).getDistrict());
                                listString.add(map);
                            }
                            SimpleAdapter aAdapter = new SimpleAdapter(getApplicationContext(), listString, R.layout.item_layout,
                                    new String[]{"name", "address"}, new int[]{R.id.poi_field_id, R.id.poi_value_id});

                            minputlist.setAdapter(aAdapter);
                            aAdapter.notifyDataSetChanged();

                        } else {
                            Toastutils.showToast("" + rCode);
                        }


                    }
                });
                inputTips.requestInputtipsAsyn();

            }

            @Override

            public void onLocateClick() {
                Log.e("onLocateClick", "重新定位...");
                mCityAdapter.updateLocateState(LocateState.LOCATING, null);
                mLocationClient.startLocation();
            }
        });

        mResultAdapter = new ResultListAdapter(this, null);
    }

    private void initView() {
        mListView = (ListView) findViewById(R.id.listview_all_city);
        mListView.setAdapter(mCityAdapter);

        TextView overlay = (TextView) findViewById(R.id.tv_letter_overlay);
        mLetterBar = (SideLetterBar) findViewById(R.id.side_letter_bar);
        mLetterBar.setOverlay(overlay);
        mLetterBar.setOnLetterChangedListener(new SideLetterBar.OnLetterChangedListener() {
            @Override
            public void onLetterChanged(String letter) {
                int position = mCityAdapter.getLetterPosition(letter);
                mListView.setSelection(position);
            }
        });


        privateEtSearchCity.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {


            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {

                String keyword = s.toString();
                if (TextUtils.isEmpty(keyword)) {
                    clearBtn.setVisibility(View.GONE);
                    emptyView.setVisibility(View.GONE);
                    mResultListView.setVisibility(View.GONE);
                } else {

                    mResultListView.setVisibility(View.VISIBLE);
                    List<City> result = dbManager.searchCity(keyword);
                    if (result == null || result.size() == 0) {
                        emptyView.setVisibility(View.VISIBLE);
                    } else {
                        emptyView.setVisibility(View.GONE);
                        mResultAdapter.changeData(result);
                    }
                }
            }
        });

        emptyView = (ViewGroup) findViewById(R.id.empty_view);
        mResultListView = (ListView) findViewById(R.id.listview_search_result);
        mResultListView.setAdapter(mResultAdapter);
        mResultListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                String name = mResultAdapter.getItem(position).getName();
                privateTvCityName.setText(name);

                privateLlScity.setVisibility(View.GONE);
                privateLlCity.setVisibility(View.VISIBLE);
                mResultListView.setVisibility(View.GONE);
                privateEtSearch.setFocusable(true);
                privateEtSearch.requestFocus();
                privateEtSearch.requestFocusFromTouch();
// TODO: 2017/3/29 城市选择好了 显示搜索的列表
                if (minputlist.getVisibility() == View.GONE) {
                    minputlist.setVisibility(View.VISIBLE);
                }


                String city = privateTvCityName.getText().toString().trim();
                String key = city;
                InputtipsQuery inputquery = new InputtipsQuery(key, city);
                inputquery.setCityLimit(true);
                Inputtips inputTips = new Inputtips(CityPickerActivity.this, inputquery);

                inputTips.setInputtipsListener(new Inputtips.InputtipsListener() {
                    @Override
                    public void onGetInputtips(final List<Tip> tipList, int rCode) {
                        if (rCode == AMapException.CODE_AMAP_SUCCESS) {
                            listString = new ArrayList<HashMap<String, String>>();
                            for (int i = 0; i < tipList.size(); i++) {
                                HashMap<String, String> map = new HashMap<String, String>();
                                map.put("name", tipList.get(i).getName());
                                map.put("address", tipList.get(i).getDistrict());
                                listString.add(map);
                            }
                            SimpleAdapter aAdapter = new SimpleAdapter(getApplicationContext(), listString, R.layout.item_layout,
                                    new String[]{"name", "address"}, new int[]{R.id.poi_field_id, R.id.poi_value_id});

                            minputlist.setAdapter(aAdapter);
                            aAdapter.notifyDataSetChanged();

                        } else {
                            Toastutils.showToast("" + rCode);
                        }


                    }
                });
                inputTips.requestInputtipsAsyn();


            }
        });

        clearBtn = (ImageView) findViewById(R.id.iv_search_clear);


        clearBtn.setOnClickListener(this);

    }


    @OnClick(R.id.iv_back)
    public void onClick() {
        finish();
    }

    @Override
    public void onClick(View v) {

    }


}